<?php
namespace haibao\classlibrary\cms\common;

class File{
	const FEATURE_FOLDER = '/feature';
	const FEATURE_TMP_FOLDER = '/tmp';
	const FEATURE_BASE_URL = 'featureview';
		
	const FILE_TYPE_IMG = 1;
	const FILE_TYPE_TXT = 2;
	const FILE_TYPE_HTML = 3;
	const FILE_TYPE_JS = 4;
	const FILE_TYPE_CSS = 5;
	
	private static $cmsDomain = '';
	private static $cmsPath = '';
	
	public static function setCmsDomainAndPath($domain,$path){
		self::$cmsDomain = $domain;
		self::$cmsPath = $path;
	}
	
	public static function getCmsDomain(){
		return self::$cmsDomain ? self::$cmsDomain : \haibao\frame\http\HttpEnvironment::domain();
	}
	
	public static function getCmsPath(){
		return self::$cmsPath ? self::$cmsPath : \haibao\frame\http\HttpEnvironment::path();
	}
	
	public static function makeNewDir($dir){
		if (!file_exists($dir)){
			mkdir($dir,0777,true);
		}
		else{
			self::removeResource($dir,false);
		}
	}
	
	public static function checkImgSize($file,&$imgInfo){
		$checked = true;
		list($width, $height) = getimagesize($file['tmp_name']);
		$imgInfo = array('width'=>$width,'height'=>$height);
		$maxSize = $width*$height;
		if ($file['size'] > $maxSize*10){
			$checked = false;
		}
		
		return $checked;
	}
	
	public static function getImgInfo($path){
		$info = getimagesize($path);
		
		return array('width'=>$info[0],'height'=>$info[1]);
	}
	
	public static function getMd5FileName($fileName){
		$data = md5($fileName).'.'.self::getFileSuffix($fileName);
		
		return $data;
	}
	
	public static function filePutContents($filePath,$content = '',$append = false){
		$dir = dirname($filePath);
		if (!file_exists($dir)){
			mkdir($dir,0777,true);
		}
		
		if ($append){
			file_put_contents($filePath,$content,FILE_APPEND);
		}
		else{
			file_put_contents($filePath,$content);
		}
	}
	
	/**
	 * 将数组转化成ini文件字符串
	 * @param array $data
	 */
	public static function getIniStrFromArr($data){
		$str = '';
		
		if ($data){
			foreach ($data as $settingName=>$settings){
				$str .= '['.$settingName.']'.PHP_EOL;
				foreach ($settings as $name=>$value){
					$str .= $name.'='.$value.PHP_EOL;
				}
			}
		}
		
		return $str;
	}
	
	public static function converToUtf8($str){
		$strCode = mb_detect_encoding($str);
		if ($strCode != 'UTF-8'){
			$str = iconv($strCode,'UTF-8',$str);
		}
		
		return $str;
	}
	
	public static function zipDir($fromPath,$toPath){
		//如果压缩文件已存在，先删除
		if (file_exists($toPath)){
			unlink($toPath);
		}
		
		$zip = new \ZipArchive();
		$zip->open($toPath,\ZipArchive::CREATE);
	
		self::addFileToZip($fromPath,$zip);
		$zip->close();
	}
	
	public static function getFileType($fileName){
		$fileType = null;
		
		$suffix = self::getFileSuffix($fileName);
		switch ($suffix){
			case 'jpg':
			case 'png':
			case 'cur':
			case 'jpeg':
			case 'gif':
			case 'bmp':
			case 'tif':
			case 'tiff':
			case 'ico':
			case 'giff':
			case 'jiff':
			case 'jfif':
			case 'jpe':
				$fileType = self::FILE_TYPE_IMG;
				break;
			case 'html':
			case 'htm':
				$fileType = self::FILE_TYPE_HTML;
				break;
			case 'js':
				$fileType = self::FILE_TYPE_JS;
				break;
			case 'css':
				$fileType = self::FILE_TYPE_CSS;
				break;
			default:
				$fileType = self::FILE_TYPE_TXT;
				break;
		}
		
		return $fileType;
	}
	
	public static function getFileStructs($srcName,$path = ''){
		$data = array();	
		if (false !== ($dir = opendir($srcName))){
			while(false !== ( $file = readdir($dir)) ) {
				if (( $file != '.' ) && ( $file != '..' )) {
					if ($path){
						$filePath = $path.'/'.$file;
					}
					else{
						$filePath = $path.$file;
					}
					
					$arr = array('name'=>self::converToUtf8($file),'path'=>self::converToUtf8($filePath));
					$fileName = $srcName . '/' . $file;
					if ( is_dir($fileName) ) {
						$arr['children'] = self::getFileStructs($fileName,$filePath);
					}
					
					//配置文件不显示
					if (self::getFileSuffix($file) == 'ini'){
						//$iniFilePath = $filePath;
					}
					else if (is_dir($fileName)){
						array_unshift($data,$arr);
					}
					else{
						array_push($data,$arr);
					}
				}
			}
	
			closedir($dir);
		}
		
		return $data;
	} 
	
	public static function checkMainFileNameFromZip($fileName){
		$checked = false;
		$res = zip_open($fileName);
		while ($id = zip_read($res)){
			if (zip_entry_open($res, $id)){
				$name = zip_entry_name($id);
				//只检测第一级目录的文件
				if (false === stripos($name,'/')){
					if ($name == 'index.html' || $name = 'index.htm'){
						$checked = true;
					} 
				}
				zip_entry_close($id);
			}
		}
		
		return $checked;
	}
	
	public static function getFileSuffix($fileName){
		$suffix = '';
		$arr = explode('.',$fileName);
		if (count($arr) >= 2){
			$suffix = array_pop($arr);
		}
		
		return $suffix;
	}
	
	public static function copyResource($src,$dst) {
		if (false !== ($dir = opendir($src))){
			if (!file_exists($dst)){
				mkdir($dst,0777,true);
			}
			while(false !== ( $file = readdir($dir)) ) {
				if (substr($file,0,1) != '.'){
					if ( is_dir($src . '/' . $file) ) {
						self::copyResource($src . '/' . $file,$dst . '/' . $file);
					}
					else {
						copy($src . '/' . $file,$dst . '/' . $file);
					}
				}
			}
			closedir($dir);
		}else if (is_file($src)){
			copy($src,$dst);
		}
	}
	
	public static function removeResource($src,$delCurrent = true){
		if (false !== ($dir = opendir($src))){
			while(false !== ( $file = readdir($dir)) ) {
				if (( $file != '.' ) && ( $file != '..' )) {
					$fileName = $src . '/' . $file;
					if ( is_dir($fileName) ) {
						self::removeResource($fileName);
					}
					else {
						unlink($fileName);
					}
				}
			}
				
			closedir($dir);
			if ($delCurrent){
				rmdir($src);
			}
		}
	}
	
	private static function addFileToZip($fromPath,$zip,$loaclDir = ''){
		$dir = opendir($fromPath);
		while(false !== ($file = readdir($dir))){
			//隐藏文件不取
			if (substr($file,0,1) != '.'){
				$filePath = $fromPath.'/'.$file;
				$localName = $loaclDir.$file;
				if (is_dir($filePath)){
					$zip->addEmptyDir($localName);
					self::addFileToZip($filePath, $zip,$loaclDir.$file.'/');
				}
				else{
					$zip->addFile($filePath,$localName);
				}
			}
		}
		closedir($dir);
	}
}